import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge, Tabs, Spin } from 'antd';
import '@/assets/css/settings';
import * as productionLayoutListService from '../../../axios/productionLayoutList'
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { isStorageList } from '../../../utils/global';
import SearchForm from './SearchForm';
import { withRouter } from 'react-router';
import { getFirstDayOfTheMonth, getDate, getDayTime } from '../../../utils/action';
import Details from './Details';
import { withPermission } from '../../../components/withpermission'
const DownLoadButton = withPermission(Button, 'download')

const { TabPane } = Tabs
class ReportProductionStatistics extends Component {
  state = {
    dataSource: [],   // 表格数据
    iconSource: [],   // 图表数据
    procedureList: [],  // 工序数据
    advanced: false,
    searchItem: {
      startTime: getFirstDayOfTheMonth(),
      endTime: getDate(),
      department: localStorage.getItem('workShop')
    },
    formData: {},
    pageSize: 10,
    pageNum: 1,
    total: 0,
    statusList: [],
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        align: 'center',
        width: 50,
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },
      {
        title: '机型',
        width: 180,
        dataIndex: 'model',
        sorter: (a, b) => compareString(a.model, b.model),
        // editable: true
      },
      {
        title: '批号',
        dataIndex: 'batchNo',
        width: 100,
        sorter: (a, b) => compareString(a.batchNo, b.batchNo)
      },
      {
        title: '工序',
        width: 150,
        // allowEllipsis: true,
        dataIndex: 'procedureName',
        sorter: (a, b) => compareString(a.procedureName, b.procedureName)
      },
      // {
      //   title: '工序编码',
      //   width: 100,
      //   // allowEllipsis: true,
      //   dataIndex: 'procedureCode',
      //   sorter: (a, b) => compareString(a.procedureCode, b.procedureCode)
      // },
      {
        title: '装配班组',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'groupName',
        sorter: (a, b) => compareString(a.groupName, b.groupName)
      },
      {
        title: '班组编码',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'groupCode',
        sorter: (a, b) => compareString(a.groupCode, b.groupCode)
      },
      {
        title: '班组长',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'groupLeader',
        sorter: (a, b) => compareString(a.groupLeader, b.groupLeader)
      },
      {
        title: '指派时间',
        width: 150,
        // allowEllipsis: true,
        dataIndex: 'assignTime',
        sorter: (a, b) => compareDate(a.assignTime, b.assignTime)
      },
      {
        title: '开工时间',
        width: 150,
        dataIndex: 'startTime',
        sorter: (a, b) => compareDate(a.startTime, b.startTime),
      },
      {
        title: '报工时间',
        width: 150,
        dataIndex: 'endTime',
        sorter: (a, b) => compareDate(a.endTime, b.endTime)
      },
      {
        title: '装配用时',
        width: 150,
        dataIndex: 'assemblyTime',
        // sorter: (a, b) => compareDate(a.assemblyTime, b.assemblyTime),
        render: (text, record, index) => {
          return record.startTime && record.endTime ? getDayTime(record.startTime, record.endTime) : ''
        }
      },
      { dataIndex: '' }
    ],
    selectedRows: [],
    selectedRowKeys: [],
    chooseRecord: {},
    activeKey: '0',
    spinning: false,
    addFrom: [],  // 车间数据
  };
  componentDidMount() {
    this.findProcedureAll()
    this.findGroupAll()
    // getDayTime('2022-04-08 09:52:16', '2022-04-09 19:55:19')

    this.setState({ statusList: isStorageList })
    if (this.props.location.data) {
      this.setState({ searchItem: this.props.location.data }, this.init)
    } else {
      this.init()
    }
  }
  componentWillUnmount() {
    this.setState = () => {
      return;
    };
  }
  init = () => {
    this.fetch()
    this.findWorkIconAll()
    // this.findProcedureAll()
  }
  // 派工班组查询
  findGroupAll = () => {
    ProductionOrderService.findGroupAll().then(res => {
      const addFrom = res.data.data
      // console.log(addFrom, '派工班组查询');
      this.setState({ addFrom });
    })
  }


  // 查询工序
  findProcedureAll = () => {
    ProductionOrderService.findProcedureAll().then(res => {
      if (res.data.code != 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      this.setState({ procedureList: res.data.data });
    })
  }

  //初始化加载表格数据
  fetch = (pageNum = 1, pageSize = 100) => {
    this.setState({ loading: true })
    const { searchItem } = this.state
    searchItem.pageNum = pageNum
    searchItem.pageSize = pageSize
    searchItem.userId = localStorage.getItem('userId')

    console.log(searchItem, 'searchItem');
    productionLayoutListService.findWorkAll(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }
  // 生产报工统计图表
  findWorkIconAll = () => {
    this.setState({ spinning: true })
    const { searchItem } = this.state
    searchItem.userId = localStorage.getItem('userId')

    productionLayoutListService.findWorkIconAll(searchItem).then(res => {
      this.setState({ spinning: false })
      if (res.data.code !== 200) {
        openModalMessage('warning', res.data.msg)
        return
      }
      this.setState({ iconSource: res.data.data })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }

  //0批量 1单独
  create = (record = {}) => {
    const { selectedRows } = this.state
    if (!selectedRows || !selectedRows.length) {
      openModalMessage('warning', '请选择要导出的单据！');
      return;
    }
    this.setState({
      chooseRecord: record
    });
  };

  handleCancel = e => {
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
      btnLoading: false
    });
    this.init();
  };


  handleSearch = () => {

    this.formSearch.validateFields((err, value) => {
      if (err) return;

      if (value.firstDeliveryDate && value.firstDeliveryDate.length === 2) {
        value.startTime = value.firstDeliveryDate[0].format('YYYY-MM-DD 00:00:00')
        value.endTime = value.firstDeliveryDate[1].format('YYYY-MM-DD 23:59:59')
        delete (value.firstDeliveryDate)
      }
      this.setState({ searchItem: value }, this.init);

    })
  };

  onHandleAdvanced = () => {
    this.setState({ advanced: !this.state.advanced })
  }
  loadData = (value, dataSource) => {
    console.log(value, dataSource)
  }
  // 选择某一行数据
  chooseRow = record => {
    let flag = true;
    let index = 0;
    this.state.selectedRowKeys.forEach((row, i) => {
      if (row == (record.batchNo + '_' + record.procedureCode)) {
        flag = false;
        index = i;
      }
    })
    const selectedRowKeys = this.state.selectedRowKeys;
    const selectedRows = this.state.selectedRows;
    if (flag) {
      selectedRowKeys.push(record.batchNo + '_' + record.procedureCode);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
  };

  onChangeTabs = activeKey => {
    this.setState({ activeKey });
  };

  resetForm = () => {
    this.formSearch && this.formSearch.resetFields();
    this.setState({
      searchItem: {
        startTime: getFirstDayOfTheMonth(),
        endTime: getDate(),
        department: localStorage.getItem('workShop')
      }
    }, this.init);
  }
  render() {
    const { addFrom, loading, dataSource, iconSource, spinning, procedureList, advanced, columns, pageNum, pageSize, total, selectedRowKeys, statusList, searchItem, } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [... this.state.selectedRowKeys];
        const rows = [... this.state.selectedRows];
        if (selected) {
          changeRows.forEach(row => {
            if (isInvalidObject(keys.find(key => key == row.batchNo + '_' + row.procedureCode))) {
              keys.push(row.batchNo + '_' + row.procedureCode);
              rows.push(row);
            }
          })
        } else {
          changeRows.forEach(row => {
            keys.splice(keys.indexOf(row.batchNo + '_' + row.procedureCode), 1);
            rows.splice(rows.indexOf(row), 1);
          })
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys })
      }
    }
    return (
      <div>
        <BasicLayoutSearch>
          <SearchForm onSearch={this.handleSearch}
            onClick={this.onHandleAdvanced}
            advanced={advanced}
            searchItem={searchItem}
            workStatusList={statusList}
            addFrom={addFrom}
            resetForm={this.resetForm}
            ref={node => (this.formSearch = node)}
          />
        </BasicLayoutSearch>
        <Tabs tabBarExtraContent={(
          <div className='mydiv'>
            {[
              <DownLoadButton key='4' onClick={() => this.create()} icon="arrow-right" />
              // <Button key={1} type="primary" onClick={() => this.create()} icon="arrow-right">导出</Button>,
            ]}
          </div>
        )}
          hideAdd
          className="layout-model"
          onChange={this.onChangeTabs}
          activeKey={this.state.activeKey}
          type="card">
          <TabPane tab={'生产报工统计'} key="0">
            <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} />
            <TableCustomize
              columns={columns}
              rowKey={(record) => record.batchNo + '_' + record.procedureCode}
              dataSource={dataSource}
              pagination={false}
              loading={loading}
              allowDrafting={true}
              allowRowEdit
              allowEditable={this.loadData}
              rowSelection={rowSelection}
              onRow={(record, rowKey) => ({
                onClick: this.chooseRow.bind(this, record, rowKey)
              })}
              rowClassName={(record, index) => {
                return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
              }}
            />
            <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
          </TabPane>
          <TabPane tab={'统计图表'} key="1">
            <Spin spinning={spinning}>
              <Details
                iconSource={iconSource}
                procedureList={procedureList}
                searchItem={searchItem}
              />
            </Spin>

          </TabPane>
        </Tabs>
      </div>
    );
  }
}
export default Form.create()(withRouter(ReportProductionStatistics));